package com.tanhua.backmanage.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.backmanage.vo.AllUsersVo;
import com.tanhua.backmanage.vo.UserInfoVo;
import com.tanhua.backmanage.vo.UserVo;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.LoginLogApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.UserStatusApi;
import com.tanhua.dubbo.server.pojo.LoginLog;
import com.tanhua.dubbo.server.pojo.UserStatus;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UsersManageServiceQQ {

    @Autowired
    private UserInfoServiceQQ userInfoServiceQQ;

    @Autowired
    private UserServiceQQ userServiceQQ;

    @Reference(version = "1.0.0")
    private UserStatusApi userStatusApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private LoginLogApi loginLogApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 查询用户列表
     *
     * @param page
     * @param pageSize
     * @param userId
     * @param nickName
     * @param city
     * @return
     */
    public AllUsersVo findAllUsers(Integer page, Integer pageSize, Integer userId, String nickName, String city) {
        //根据用户id查询
        if (userId != null) {
            IPage<UserInfo> userInfoPage = queryUsersListByUserId(page, pageSize, Long.valueOf(userId));
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        //根据用户昵称模糊查询
        if (!ObjectUtil.isEmpty(nickName)) {
            IPage<UserInfo> userInfoPage = queryUsersListByNickName(page, pageSize, nickName);
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        //根据城市模糊查询
        if (!ObjectUtil.isEmpty(city)) {
            IPage<UserInfo> userInfoPage = queryUsersListByCity(page, pageSize, city);
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        //查询当页用户数据
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        IPage<UserInfo> userInfoIPage = userInfoServiceQQ.queryByPage(queryWrapper, userInfoPage);
        List<UserVo> userVos = getUserVos(userInfoPage);
        if (userVos == null) {
            return null;
        }
        return getPageResult(page, pageSize, userInfoIPage, userVos);
    }


    //分页信息封装
    private AllUsersVo getPageResult(Integer page, Integer pageSize, IPage<UserInfo> userInfoIPage, List<UserVo> userVos) {
//       创建返回集
        AllUsersVo allUsersVo = new AllUsersVo();
        //QueryWrapper<UserInfo> query = new QueryWrapper<>();
        //List<UserInfo> userInfos = userInfoMapper.selectList(query);

        //取余加一获取总页数
        int pages = userVos.size() % page == 0 ? userVos.size() / page : userVos.size() / page + 1;

      //设置参数
        allUsersVo.setPages(pages);
        allUsersVo.setCounts(userVos.size());
        allUsersVo.setPage(page);
        allUsersVo.setPagesize(pageSize);
        //创建集合截数据
        List<UserVo> userVos1 = new ArrayList<>();
        System.out.println(userVos);
        //               0  当前页                       10  实现页数据
        for (int i = (page - 1) * pageSize; i < page * pageSize; i++) {
            if (i > userVos.size() - 1) {
                allUsersVo.setItems(userVos1);
                return allUsersVo;
            }
//        循环添加
            userVos1.add(userVos.get(i));
        }
//        设置列表
        allUsersVo.setItems(userVos1);
        //System.out.println(userVos1);

//        返回10调数据

        return allUsersVo;
    }

    //UserVo数据封装
    private List<UserVo> getUserVos(IPage<UserInfo> userInfoPage) {
        List<UserInfo> records = userInfoPage.getRecords();
        List<UserVo> userVos = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        //将userInfo的数据封装到userVo中
        for (UserInfo record : records) {
            UserVo userVo = new UserVo();
            userVo.setId(record.getUserId());
            ids.add(record.getUserId());
            userVo.setAge(record.getAge());
            userVo.setCity(record.getCity());
            userVo.setLogo(record.getLogo());
            userVo.setNickname(record.getNickName());
            userVo.setSex(record.getSex().getValue() == 1 ? "男" : "女");
            //查询日志,将最近活跃时间封装到userVo中
            LoginLog loginLog = loginLogApi.getLoginLogById(record.getUserId());
            if(loginLog == null){
                long time = record.getCreated().getTime();
                userVo.setLastActiveTime(time);
            }else{
                Long logTime = loginLog.getLogTime();
                userVo.setLastActiveTime(logTime);

            }

            // userVo.setLastActiveTime("2000-01-01 05:08");
            userVos.add(userVo);
        }
        if (CollectionUtils.isEmpty(userVos) || CollectionUtils.isEmpty(ids)) {
            return null;
        }
        //查询userStatus,将状态信息封装到userVo中
        List<UserStatus> userStatuses = userStatusApi.queryUserStatus(ids);
        if (CollectionUtils.isEmpty(userStatuses)) {
            for (UserVo userVo : userVos) {
                userVo.setUserStatus("1");
            }
        } else {
            //若userStatus中有数据,查看是否已到解冻时间,若到,将userStaus中数据删除
            for (UserVo userVo : userVos) {
                for (UserStatus userStatus : userStatuses) {
                    if (userVo.getId().longValue() == userStatus.getUserId().longValue()) {
                        Date now = new Date();
                        Long expireTime = userStatus.getExpireTime();
                        if (now.getTime() > expireTime) {
                            userVo.setUserStatus("1");
                            unFreezeUser(userVo.getId().intValue());
                        }
                        userVo.setUserStatus("2");
                        break;
                    }
                }
            }
            for (UserVo userVo : userVos) {
                if (userVo.getUserStatus() == null) {
                    userVo.setUserStatus("1");
                }
            }
        }
        List<User> users = userServiceQQ.queryUserList(ids);
        for (UserVo userVo : userVos) {
            for (User user : users) {
                if (userVo.getId().longValue() == user.getId().longValue()) {
                    userVo.setMobile(user.getMobile());
                }
            }
        }
        return userVos;
    }

    //根据用户id查询
    private IPage<UserInfo> queryUsersListByUserId(Integer page, Integer pageSize, Long userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("user_id", userId);
        IPage<UserInfo> userInfoIPage = userInfoServiceQQ.queryByPage(queryWrapper, userInfoPage);
        return userInfoIPage;
    }


    //根据用户昵称查询
    private IPage<UserInfo> queryUsersListByNickName(Integer page, Integer pageSize, String nickName) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("nick_name", nickName);
        IPage<UserInfo> userInfoIPage = userInfoServiceQQ.queryByPage(queryWrapper, userInfoPage);
        return userInfoIPage;
    }

    //根据城市模糊查询
    private IPage<UserInfo> queryUsersListByCity(Integer page, Integer pageSize, String city) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("city", city);
        IPage<UserInfo> userInfoIPage = userInfoServiceQQ.queryByPage(queryWrapper, userInfoPage);
        return userInfoIPage;
    }


    /**
     * 查询单个用户详细信息
     *
     * @param userId
     * @return
     */
    public UserInfoVo queryUserInfo(Long userId) {
        UserInfo userInfo = userInfoServiceQQ.queryById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setAge(userInfo.getAge());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setIncome(userInfo.getIncome());
        userInfoVo.setCoverPic(userInfo.getCoverPic());
        userInfoVo.setLogo(userInfo.getLogo());
        userInfoVo.setMarriage(userInfo.getMarriage());
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setOccupation(userInfo.getIndustry());
        userInfoVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
        userInfoVo.setTags(userInfo.getTags());
        UserStatus userStatus = userStatusApi.queryUserStatusById(userId);

        //若userStatus中有数据,查看是否已到解冻时间,若到,将userStaus中数据删除
        if (userStatus == null) {
            userInfoVo.setUserStatus("1");
        } else {
            Date now = new Date();
            Long unfreeze = userStatus.getExpireTime();
            if (now.getTime() > unfreeze) {
                userInfoVo.setUserStatus("1");
                unFreezeUser(userInfoVo.getId().intValue());
            }
            userInfoVo.setUserStatus("2");
        }

        //查询日志,将最近活跃时间封装到userVo中
        LoginLog loginLog = loginLogApi.getLoginLogById(userId);
        if(loginLog == null){
            long time = userInfo.getCreated().getTime();
            userInfoVo.setLastActiveTime(time);
        }else{
            Long logTime = loginLog.getLogTime();
            userInfoVo.setLastActiveTime(logTime);

        }

       // userInfoVo.setLastActiveTime("2000-01-01 05:08");

        //粉丝数
        Long fanCount = userLikeApi.queryFanCount(userId);
        //互相喜欢数（配对人数）
        Long eachLikeCount = userLikeApi.queryEachLikeCount(userId);
        //喜欢数
        Long likeCount = userLikeApi.queryLikeCount(userId);
        userInfoVo.setCountLiked(likeCount.intValue());
        userInfoVo.setCountBeLiked(fanCount.intValue());
        userInfoVo.setCountMatching(eachLikeCount.intValue());

        //查询用户上一次登录地址
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(userId);
        userInfoVo.setLastLoginLocation(userLocationVo.getAddress());
        //userInfoVo.setLastLoginLocation(userInfo.getCity());
        User user = userServiceQQ.queryUserById(userId);
        userInfoVo.setMobile(user.getMobile());
        userInfoVo.setCreated(Long.valueOf(user.getCreated().getTime()).intValue());
        return userInfoVo;
    }


    //冻结用户
    public String freezeUser(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        if (userId == null || freezingTime == null || freezingRange == null || reasonsForFreezing == null || frozenRemarks == null) {
            return null;
        }
        UserStatus userStatus = new UserStatus();
        userStatus.setId(ObjectId.get());
        userStatus.setUserId(Long.valueOf(userId));
        userStatus.setFreezingTime(freezingTime);
        userStatus.setFreezingRange(freezingRange);
        userStatus.setFrozenRemarks(frozenRemarks);
        userStatus.setReasonsForFreezing(reasonsForFreezing);
        userStatus.setCreated(new Date().getTime());

        Long freezeTime = null;
        switch (freezingTime) {
            case 1:
                freezeTime = userStatus.getCreated() + 60 * 60 * 24 * 100 * 3L;
                break;
            case 2:
                freezeTime = userStatus.getCreated() + 60 * 60 * 24 * 100 * 7L;
                break;
            case 3:
                freezeTime = 0L;
                break;
        }

        userStatus.setExpireTime(freezeTime);

        String key = "USER_FREEZE_RANGE_" + userStatus.getUserId();

        Long timeout = freezeTime - System.currentTimeMillis();
        timeout = timeout < 0 ? -1 : timeout;

        redisTemplate.opsForValue().set(key, userStatus.getFreezingRange().toString(), timeout, TimeUnit.MILLISECONDS);

        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
        Object res = redisTemplate.opsForValue().get(key);
        System.out.println("res = " + res);
        System.out.println("expire = " + expire);

        //System.out.println(userStatus.getId());
        //System.out.println(userStatus.getUserId());
        //System.out.println(userStatus.getFreezingTime());
        //System.out.println(userStatus.getFreezingRange());
        //System.out.println(userStatus.getReasonsForFreezing());
        //System.out.println(userStatus.getFrozenRemarks());
        //System.out.println(userStatus.getCreated());
        //System.out.println(userStatus.getExpireTime());
        return userStatusApi.saveUserStatus(userStatus);
    }

    //解冻用户
    public Boolean unFreezeUser(Integer userId) {
        if (userId == null) {
            return null;
        }
        if (!redisTemplate.hasKey("USER_FREEZE_RANGE_" + userId)) {
            return null;
        }
        Boolean result = userStatusApi.deleteUserStatus(Long.valueOf(userId));
        if (result) {
            Boolean delete = redisTemplate.delete("USER_FREEZE_RANGE_" + userId);
            return delete;
        } else {
            return false;
        }
    }
}
